package com.example.demo1;

import static com.example.demo1.tool.screenshot.ScreenActivity.requestCode_Projection;
import static com.example.demo1.tool.screenshot.Service1.GetScreen;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.PermissionChecker;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.AppOpsManager;
import android.app.usage.UsageEvents;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;

import com.example.demo1.tool.screenshot.ScreenActivity;

import java.lang.reflect.Field;
import java.util.Calendar;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final int SCREEN_CAPTURE = 7777;

    public static String getApplicationNameByPackageName(Context context, String packageName) {
        PackageManager pm = context.getPackageManager();
        String Name ;
        try {
            Name=pm.getApplicationLabel(pm.getApplicationInfo(packageName,PackageManager.GET_META_DATA)).toString();
        } catch (PackageManager.NameNotFoundException e) {
            Name = "";
        }
        return Name;
    }
    private Context context = this;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //添加存储权限；
        addPerssion();

        ActivityManager activityManager = (ActivityManager)context.getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName runningTopActivity = activityManager.getRunningTasks(1).get(0).topActivity;
//        startActivityForResult(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS),809);
        if (!hasPermission())
            startActivityForResult(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS),809);
        getAPPName();
        Button bt = findViewById(R.id.bt);
    }
    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    private static String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE" };
    public void addPerssion(){
        String[] Permission={
                Manifest.permission.WRITE_EXTERNAL_STORAGE};
        int permission = ActivityCompat.checkSelfPermission(this,
                "android.permission.WRITE_EXTERNAL_STORAGE");
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // 没有写的权限，去申请写的权限，会弹出对话框
            ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);
        }
    }

    //判断使用访问记录权限
    private boolean hasPermission() {
        AppOpsManager appOpsM = (AppOpsManager)
                getSystemService(Context.APP_OPS_SERVICE);

        int mode = 0;

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            mode = appOpsM.checkOpNoThrow(AppOpsManager.OPSTR_GET_USAGE_STATS,
                    android.os.Process.myUid(), getPackageName());
        }
        return mode == AppOpsManager.MODE_ALLOWED;
    }



    //每隔一段时间（TINE）获取前端APP的Name；
    public static int TIME = 10000;
    private void getAPPName(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(true){
                    try {
                        Thread.sleep(TIME);
                        String appName = getApplicationNameByPackageName(context,getTopProcessPackageName(context));
                        //appName = getTopProcessPackageName(context);

                        System.out.println(appName);
                        System.out.println("****************************************");
                        if(appName.equals("哔哩哔哩")){
                            GetScreen();
                        }

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }


    public void jieping(View v){
        ScreenActivity.Init(context);
    }


    public static String getForegroundPackageName(Context context) {
        //Get the app record in the last month
        Calendar calendar = Calendar.getInstance();
        final long end = calendar.getTimeInMillis();
        calendar.add(Calendar.MONTH, -1);
        final long start = calendar.getTimeInMillis();

        UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        UsageEvents usageEvents = usageStatsManager.queryEvents(start, end);
        UsageEvents.Event event = new UsageEvents.Event();
        String packageName = null;
        while (usageEvents.hasNextEvent()) {
            usageEvents.getNextEvent(event);
            if (event.getEventType() == UsageEvents.Event.ACTIVITY_RESUMED) {

                packageName = event.getPackageName();
            }
        }
        return packageName;
    }
    public static String getTopProcessPackageName(Context context) {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
            /** 在2022/06/22该段代码已弃用
             UsageStats usageStats = getTopUsageStats(context);
             if (usageStats != null) {
             return usageStats.getPackageName();
             }**/
            return getForegroundPackageName(context);
        } else {
            ActivityManager.RunningAppProcessInfo info = getTopProcessInfo(context);
            if (info != null) {
                System.out.println("ProcessName: " + info.processName);
                return info.processName;
            }
        }
        System.out.println("进程名为null");
        return null;
    }

    public static ActivityManager.RunningAppProcessInfo getTopProcessInfo(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();
        if (processes != null && processes.size() > 0) {
            for (ActivityManager.RunningAppProcessInfo info : processes) {
                if (info.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    return info;
                }
            }
        }
        return null;
    }
}